package com.bbcare.comm.ExcelUtil;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bbcare.comm.ExcelUtil.ExcelUtil.ExcelExportData;

/**
 * 文件下载帮助类
 * @ClassName: FileDownloadUtils 
 * @author zhengguoyong
 */
public class FileDownloadUtils {

	/**
	 * 对下载后的文件名进行url编码处理
	 * @param userAgent 请求头中的User-Agent
	 * @param fileName  文件名称
	 * @author zhengguoyong
	 */
	public static String downFileNameUrlCode(String userAgent,String fileName){
		String tmpFileName="";
		try {
			if (userAgent.contains("MSIE")||userAgent.contains("Trident")) {
			    tmpFileName = java.net.URLEncoder.encode(fileName, "UTF-8");
			}else{
				tmpFileName = new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
			}
		} catch (UnsupportedEncodingException e) {}
		return tmpFileName;
	}
	/**
	 * 导出文件
	 * @param request 请求对象
	 * @param response 响应对象
	 * @param exportData 待导出数据
	 * @param fileName   导出文件名(格式：xxxxxx)
	 * @author zhengguoyong
	 */
	public static void exportFile(HttpServletRequest request,HttpServletResponse response,ExcelExportData exportData,String fileName){
		exportFile(response, exportData, downFileNameUrlCode(request.getHeader("User-Agent"),fileName+".xls"));
	}
	/**
	 * 导出文件
	 * @param response 响应对象
	 * @param exportData 待导出数据
	 * @param fileName   导出文件名使用URL进行编码（格式：xxxx.xls）
	 * @author zhengguoyong
	 */
	public static void exportFile(HttpServletResponse response,ExcelExportData exportData,String fileName){
		//捕获异常信息
		try {
			//ByteArrayOutputStream os = 
			//response.getOutputStream().write(os.toByteArray());
			response.setContentType("text/html;charset=utf-8");
			response.setContentType("application/x-msdownload;");
			response.setHeader("Content-disposition", "attachment; filename=" + fileName);
			ExcelUtil.export2Stream(exportData, response.getOutputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
